package com.swust.exam.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.swust.exam.pojo.Classes;
import com.swust.exam.pojo.Students;
import com.swust.exam.service.ClassesService;
import com.swust.exam.service.StudentsService;

@Controller
@RequestMapping(value="/Student")
public class StudentsController {
	private static Logger logger  = Logger.getLogger(StudentsController.class);  
    private final static String xls = "xls";  
	@Autowired
	private StudentsService studentsservice;
	@Autowired
	private ClassesService classservice;
	
	@RequestMapping(value="/get")
	public Students get(int id) {
		return studentsservice.get(id);
	}
	
	@RequestMapping(value="/delete")
	public String delete(int id,Model model) {
		studentsservice.delete(id);
		List<Students> studentslist=studentsservice.GetDetailStudentInfo();
		List<Classes> classlist=classservice.GetDetailClasses();
		List<Classes> CourseNamelist=classservice.GetCourseName();
		model.addAttribute("CourseNamelist",CourseNamelist);
		model.addAttribute("classlist",classlist);
		model.addAttribute("studentslist",studentslist);
		return "students";
	}
	
	
	@RequestMapping(value="/insert")
	public String insert(Students info ,Model model) {
		studentsservice.insert(info);	
		List<Students> studentslist=studentsservice.GetDetailStudentInfo();
		List<Classes> classlist=classservice.GetDetailClasses();
		List<Classes> CourseNamelist=classservice.GetCourseName();
		model.addAttribute("CourseNamelist",CourseNamelist);
		model.addAttribute("classlist",classlist);
		model.addAttribute("studentslist",studentslist);
		return "students";
	}
	
	@RequestMapping(value="/update")
	public String update(Students info,Model model) {
		studentsservice.update(info);
		List<Students> studentslist=studentsservice.GetDetailStudentInfo();
		List<Classes> classlist=classservice.GetDetailClasses();
		List<Classes> CourseNamelist=classservice.GetCourseName();
		model.addAttribute("CourseNamelist",CourseNamelist);
		model.addAttribute("classlist",classlist);
		model.addAttribute("studentslist",studentslist);
		return "students";
	}
	
	@RequestMapping(value="/fileUpload")
	@ResponseBody
	public String fileUpload(HttpServletRequest request,@RequestParam("fileName") MultipartFile file) throws IOException{
		java.util.Calendar c=java.util.Calendar.getInstance();
		java.text.SimpleDateFormat f=new java.text.SimpleDateFormat("yyyy.MM.dd.hh.mm.ss.");
		//System.out.println(f.format(c.getTime()));   
//		Date day=new Date(); 
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		System.out.println(df.format(day)); 
		if(file.isEmpty()){
	            return "提交失败";
	        }
	       String fileName = f.format(c.getTime()) + file.getOriginalFilename();
	       File directory = new File("");// 参数为空  
	       String courseFile = directory.getCanonicalPath();
	       String path = courseFile + "\\src\\main\\resources\\static\\uploadfile";
	       //System.out.println(path);  //查看路径
	       File dest = new File(path + "/" + fileName);
	       if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
	            dest.getParentFile().mkdir();
	        }
	        try {
	        	file.transferTo(dest); //保存文件
	            studentsservice.BulkImport(readexcel(path,fileName,file));//阅读文件并生成list传递到数据库
	            return "提交成功";
	        } catch (IllegalStateException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return "提交失败";
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return "提交失败";
	        }
	    }
	
	public List<Students> readexcel(String path,String fileName,MultipartFile file) throws IOException{
	   	 //检查文件是否合理
		 checkFile(file);
	   	 FileInputStream excelFileInputStream = new FileInputStream(path + "/" +fileName);
		  //获得Workbook工作薄对象  
		  Workbook workbook = new HSSFWorkbook(excelFileInputStream);  

	        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回  
	        List<Students> list = new ArrayList<Students>();  
	        if(workbook != null){  
	            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
	                //获得当前sheet工作表  
	                Sheet sheet = workbook.getSheetAt(sheetNum);  
	                if(sheet == null){  
	                    continue;  
	                }  
	                //获得当前sheet的开始行  
	                int firstRowNum  = sheet.getFirstRowNum();  
	                //获得当前sheet的结束行  
	                int lastRowNum = sheet.getLastRowNum();  
	                //循环除了第一行的所有行  
	                for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){  
	                    //获得当前行  
	                    Row row = sheet.getRow(rowNum);  
	                    if(row == null){  
	                        continue;  
	                    }  
	                    //获得当前行的开始列  
	                    int firstCellNum = row.getFirstCellNum();  
	                    //获得当前行的列数  
	                    int lastCellNum = row.getPhysicalNumberOfCells();  
	                    //循环当前行  
	                    Students st = new Students();
	                    for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
	                        Cell cell = row.getCell(cellNum); 
	                        switch (cellNum) {
	                        	case 0:int classid=Integer.parseInt(getCellValue(cell));
	                        		   st.setClassId(classid);
	                        	case 1:st.setStudentNumber(getCellValue(cell));
	                        	case 2:st.setStudentName(getCellValue(cell));
	                        	case 3:st.setStudentClass(getCellValue(cell));
	                        	case 4:st.setStudentGrade(getCellValue(cell));
	                        	case 5:st.setStudentPassword(getCellValue(cell));
	                        }
	                        System.out.println(cell);
	                    } 
	                    list.add(st);  
	                }  
	            }  
	            //((FileInputStream) workbook).close(); 
	        }  
	        return list;
	}
	
	//检查是否是excel
	 	public static void checkFile(MultipartFile file) throws IOException{  
	        //判断文件是否存在  
	        if(null == file){  
	            logger.error("文件不存在！");  
	            throw new FileNotFoundException("文件不存在！");  
	        }  
	        //获得文件名  
	        String fileName = file.getOriginalFilename();  
	        //判断文件是否是excel文件  
	        if(!fileName.endsWith(xls) ){  
	            logger.error(fileName + "不是excel文件");  
	            throw new IOException(fileName + "不是excel文件");  
	        }  
	    }  

	//获得excel中cell的元素
	 	public static String getCellValue(Cell cell){  
	        String cellValue = "";  
	        if(cell == null){  
	            return cellValue;  
	        }  
	        //把数字当成String来读，避免出现1读成1.0的情况  
	        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){  
	            cell.setCellType(Cell.CELL_TYPE_STRING);  
	        }  
	        //判断数据的类型  
	        switch (cell.getCellType()){  
	            case Cell.CELL_TYPE_NUMERIC: //数字  
	                cellValue = String.valueOf(cell.getNumericCellValue());  
	                break;  
	            case Cell.CELL_TYPE_STRING: //字符串  
	                cellValue = String.valueOf(cell.getStringCellValue());  
	                break;  
	            case Cell.CELL_TYPE_BOOLEAN: //Boolean  
	                cellValue = String.valueOf(cell.getBooleanCellValue());  
	                break;  
	            case Cell.CELL_TYPE_FORMULA: //公式  
	                cellValue = String.valueOf(cell.getCellFormula());  
	                break;  
	            case Cell.CELL_TYPE_BLANK: //空值   
	                cellValue = "";  
	                break;  
	            case Cell.CELL_TYPE_ERROR: //故障  
	                cellValue = "非法字符";  
	                break;  
	            default:  
	                cellValue = "未知类型";  
	                break;  
	        }  
	        return cellValue;  
	    }  
}
